package com.guxingke.typecho4j.widget.handle.option;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.jfinal.model.Option;
import com.guxingke.typecho4j.route.DispatcherStrategy;
import com.guxingke.typecho4j.route.Route;
import com.guxingke.typecho4j.route.Routes;
import com.guxingke.typecho4j.widget.WidgetHandle;
import com.guxingke.typecho4j.widget.layout.LayoutWidget;
import com.guxingke.typecho4j.widget.layout.back.ProfileLayoutWidget;
import com.guxingke.typecho4j.widget.provider.OptionBaseWidget;
import com.jfinal.core.Controller;

/**
 * 更新编辑配置的处理组件
 * 
 * @author guxingke
 *
 */
public class UpdateEditOptionHandleWidget extends OptionBaseWidget implements
		WidgetHandle {
	private Set<String> options = new HashSet<String>();

	@Override
	public boolean init() {
		initLogger();
		options.add("comment");
		options.add("ping");
		options.add("feed");
		return true;
	}

	@Override
	public void handle(Controller controller) throws Typecho4jException {
		String[] temps = controller.getParaValues("defaultAllow[]");
		List<String> list = Arrays.asList(temps);
		
		for (String option : options) {
			if (list.contains(option)) {
				if ("comment".equals(option)) {
					setValue(new Option().set("name",
							"defaultAllowComment")
							.set("value", "1"));
				} else if ("ping".equals(option)) {
					setValue(new Option().set("name",
							"defaultAllowPing")
							.set("value", "1"));
				} else if ("feed".equals(option)) {
					setValue(new Option().set("name",
							"defaultAllowFeed")
							.set("value", "1"));
				}
			} else {
				if ("comment".equals(option)) {
					setValue(new Option().set("name",
							"defaultAllowComment")
							.set("value", "0"));
				} else if ("ping".equals(option)) {
					setValue(new Option().set("name",
							"defaultAllowPing")
							.set("value", "0"));
				} else if ("feed".equals(option)) {
					setValue(new Option().set("name",
							"defaultAllowFeed")
							.set("value", "0"));
				}
			}
		}

		// 刷新Provider的状态
		LayoutWidget.refreshLayout(ProfileLayoutWidget.class);
	}

	@Override
	public void configRoute(Routes routes) {
		Route updateEditOptionRoute = new Route("updateEditOption",
				this.getClass(), "/admin/profile",
				DispatcherStrategy.REDIRECT);
		routes.addRoute(updateEditOptionRoute);
	}
}
